package cn.mymall.service.impl;

import cn.mymall.entity.Menu;
import cn.mymall.entity.UserMenu;
import cn.mymall.mapper.MenuMapper;
import cn.mymall.service.IMenuService;
import cn.mymall.service.IUserMenuService;
import cn.mymall.util.BeanUtil;
import cn.mymall.vo.menu.MenuReqVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 后台菜单表 服务实现类
 * </p>
 *
 * @author liqilun
 * @since 2022-10-23
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private IUserMenuService userMenuService;
    @Override
    public List<Menu> getMenuList(MenuReqVo reqVo) {
        QueryWrapper qw = new QueryWrapper();
        if(reqVo.getId() != null){
            qw.eq("id", reqVo.getId());
        }

        if(StringUtils.isNotBlank(reqVo.getMenuName())){
            qw.like("menu_name", reqVo.getMenuName());
        }

        if(reqVo.getParentStatus() == 1){
            qw.isNull("parent_id");
        }

        if(StringUtils.isNotBlank(reqVo.getMenuType())){
            qw.eq("menu_type", reqVo.getMenuType());
        }

        qw.orderByAsc("sort_num","id");
        return list(qw);
    }

    @Override
    public List<Menu> getUserMenuShowList(Integer userId) {
        List<UserMenu> userMenus = userMenuService.listByMap(ImmutableMap.of("user_id",userId));
        List<Integer> menuIdList = BeanUtil.getBeanPropertyList(userMenus,"menuId",true);
        if(CollectionUtils.isEmpty(menuIdList)) return Collections.emptyList();
        List<Integer> parentMenuIdList = new ArrayList<>();
        for(Integer menuId : menuIdList){
            Menu menu = getById(menuId);
            if (menu.getParentId() != null &&
                    !menuIdList.contains(menu.getParentId()) && !parentMenuIdList.contains(menu.getParentId())) {
                parentMenuIdList.add(menu.getParentId());
            }
        }
        parentMenuIdList.addAll(menuIdList);
        QueryWrapper qw = new QueryWrapper();
        qw.in("id",parentMenuIdList);
        qw.orderByAsc("sort_num","id");
        return list(qw);
    }

    @Override
    public List<Menu> getUserMenuList(Integer userId) {
        List<UserMenu> userMenus = userMenuService.listByMap(ImmutableMap.of("user_id",userId));
        List<Integer> menuIdList = BeanUtil.getBeanPropertyList(userMenus,"menuId",true);
        if(CollectionUtils.isEmpty(menuIdList)) return Collections.emptyList();
        QueryWrapper qw = new QueryWrapper();
        qw.in("id",menuIdList);
        qw.isNotNull("parent_id");
        qw.orderByAsc("sort_num","id");
        return list(qw);
    }
}
